package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.kiwi.utils.JsonBinder;
import com.iqiyi.pps.epg.api.aop.annotation.SkipAuthCheck;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.model.web.broadcast.TProgramPlatformControl;
import com.iqiyi.pps.epg.api.model.web.channel.TChannel;
import com.iqiyi.pps.epg.api.model.web.program.*;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.query.TResponse;
import com.iqiyi.pps.epg.api.server.web.broadcast.BroadcastControlWebService;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebService;
import com.iqiyi.pps.epg.api.server.web.program.ProgramWebService;
import com.iqiyi.pps.epg.api.utils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by karkarrotxu on 2016/9/8.
 */
@Service
public class ProgramProxy extends BaseProxy {

    private static Logger logger = LoggerFactory.getLogger(ProgramProxy.class);

    @SkipAuthCheck
    public String getRtmpStream(String qipuId) {
        try {
            if (StringUtils.isNotBlank(qipuId)) {
                if (!RegUtil.checkProgramQipuId(qipuId)) {
                    return Constants.getJsonResponse(Constants.CODE_ERROR, null, ERROR_PROGRAM_QIPU_ID_FORMAT);
                }
            }
            Map<String, String> params = new HashMap();
            params.put("qipuId", qipuId);
            ProgramWebService.Iface service = getProgramService();
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TResponse tResponse = service.getRtmpStream(tFilter);
            boolean success = Constants.CODE_SUC.equals(tResponse.getCode());
            if (success) {
                return Constants.getJsonResponse(Constants.CODE_SUC, JSON.parseObject(tResponse.getJsonData()), null);
            } else {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR);
            }
        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][getRtmpStream]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getProgramLogList(String programId, Integer pageNo, Integer pageSize) {
        if (!RegUtil.isPositiveInteger(programId)) {
            return ServiceUtil.getResponseFail(ERROR_PROGRAM_ID_FORMAT);
        }
        try {
            pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
            pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
            ProgramWebService.Iface service = getProgramService();
            Map<String, String> params = new HashMap<>();
            TFilter tFilter = new TFilter();
            params.put("EQL_programId", programId + "");
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "id", "desc", true);
            TProgramLogPage tProgramLogPage = service.getProgramLogList(page, tFilter);
            if (tProgramLogPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, tProgramLogPage, "操作成功").toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getProgramLogList] pId=" + programId, e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getProgramList(String programId, String fatherId, String startDate,
                                 String endDate, Integer pageNo, Integer pageSize, String qipuId,
                                 String pname, String freeStatus, String bossStatus, String liveProgramType,
                                 String channelName, String liveType, String liveChannelType, String sortType,
                                 String deleteStatus, String formal, String playStatus, String episodeGrade,
                                 String recommendRate, String hot, String test, String fromPath) {
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        deleteStatus = (null == deleteStatus) ? "0" : deleteStatus;
        Map<String, String> params = new HashMap();
        // params.put("type", type);
        if (deleteStatus.equals("0")) {
            params.put("EQI_program.is_delete", deleteStatus);
            params.put("NEQI_channel.is_enable", -1 + "");
        } else if (deleteStatus.equals("1")) {
            params.put("EQI_program.is_delete", deleteStatus);
        }

        if (StringUtils.isNotEmpty(fatherId)) {
            params.put("EQI_program.father_id", fatherId);
        }
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() != 10 && startDate.length() != 19) {
                return ServiceUtil.getResponseError(ERROR_DATE_FORMAT);
            }
            if (startDate.length() == 10) {
                startDate += " 00:00:00";
            }
            params.put("GET_program.start_play_time", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() != 10 && endDate.length() != 19) {
                return ServiceUtil.getResponseError(ERROR_DATE_FORMAT);
            }
            if (endDate.length() == 10) {
                endDate += " 00:00:00";
            }
            params.put("LET_program.start_play_time", endDate);
        }
        if (StringUtils.isNotEmpty(programId)) {
            params.put("EQL_program.id", programId);
        }
        if (StringUtils.isNotEmpty(qipuId)) {
            params.put("EQL_program.qipu_id", qipuId);
        }
        if (StringUtils.isNotEmpty(pname)) {
            params.put("LIKES_program.program_name", pname.trim());
        }
        if (StringUtils.isNotEmpty(freeStatus)) {
            params.put("EQI_program.status", freeStatus);
        }

        if (StringUtils.isNotEmpty(bossStatus)) {
            params.put("EQS_program.boss_status", bossStatus);
        }

        if (StringUtils.isNotEmpty(liveProgramType)) {
            params.put("EQI_program.type", liveProgramType);
        }

        if (StringUtils.isNotEmpty(channelName)) {
            params.put("LIKES_channel.name", channelName);
        }

        if (StringUtils.isNotEmpty(liveType)) {
            params.put("EQI_channel.live_type", liveType);

            // 2 为临时直播
            if (liveType.equals("2")) {
                if (StringUtils.isNotEmpty(hot)) {
                    params.put("EQI_program.hot", hot);
                }
                if (StringUtils.isNotEmpty(test)) {
                    params.put("EQI_program.test", test);
                }
            }
        }
        if (StringUtils.isNotEmpty(recommendRate)) {
            params.put("EQI_program.recommend_rate", recommendRate);
        }
        if (StringUtils.isNotEmpty(liveChannelType)) {
            params.put("EQI_channel.type", liveChannelType);
        }
        String useSortType = "asc";
        if ("desc".equalsIgnoreCase(sortType)) {
            useSortType = "desc";
        }
        if (StringUtils.isNotEmpty(formal)) {
            params.put("EQI_channel.formal", formal);
        }
        PlayStatusUtil.addParamsByPlayStatus(params, playStatus);
        if (StringUtils.isNotEmpty(episodeGrade)) {
            params.put("EQI_program.episode_grade", episodeGrade);
        }

        if (StringUtils.isEmpty(fatherId) &&
                StringUtils.isEmpty(startDate) &&
                StringUtils.isEmpty(endDate) &&
                StringUtils.isEmpty(programId) &&
                StringUtils.isEmpty(qipuId) &&
                StringUtils.isEmpty(pname) &&
                StringUtils.isEmpty(freeStatus) &&
                StringUtils.isEmpty(bossStatus) &&
                StringUtils.isEmpty(liveProgramType) &&
                StringUtils.isEmpty(channelName) &&
                StringUtils.isEmpty(liveType) &&
                StringUtils.isEmpty(liveChannelType) &&
                StringUtils.isEmpty(formal) &&
                StringUtils.isEmpty(playStatus) &&
                StringUtils.isEmpty(episodeGrade)
                ) {
            params.put("GET_program.start_play_time", DateTimeUtil.transShortFormat(System.currentTimeMillis() - DateTimeUtil.DAY_TIME * 2) + " 00:00:00");
        }
        TFilter tFilter = new TFilter();
        tFilter.setFilters(params);
        TPage page = null;

        TProgramPage tProgramPage = null;
        try {
            if (fromPath != null && "library".compareTo(fromPath) == 0) {
                page = new TPage(-1, pageNo, pageSize, "start_play_time", useSortType, true);
                tProgramPage = getProgramService().findProgramLibrary(page, tFilter);
            } else {
                page = new TPage(-1, pageNo, pageSize, "start_play_time,last_sort_time,id", useSortType + ",desc,asc", true);
                tProgramPage = getProgramService().findProgramPage(page, tFilter);
            }
            boolean success = tProgramPage != null;
            if (success) {
                return Constants.getResponse(Constants.CODE_SUC, tProgramPage, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (TException e) {
            logger.error("[programList]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String currentAndNextProgram(String fatherId) {
        String listString = null;
        if (!RegUtil.isPositiveInteger(fatherId)) {
            return ServiceUtil.getResponseFail(ERROR_CHANNEL_ID_FORMAT);
        }
        try {
            listString = getProgramService().searchCurrentAndNextProgram(new Long(fatherId));
            JsonBinder binder = JsonBinder.buildNormalBinder();
            List<Map<String, Object>> beanList = binder.getMapper().readValue(listString, new TypeReference<List<Map<String, Object>>>() {
            });
            return Constants.getJsonResponse(Constants.CODE_SUC, beanList, null);
        } catch (Exception e) {
            logger.error("[currentAndNextProgram] fatherId =" + fatherId, e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    @SkipAuthCheck
    public String searchProgram(String name, String startDate, String endDate,
                                String porgramQipuId, String channelQipuId, String channelName) {
        if (StringUtils.isBlank(name) && StringUtils.isBlank(porgramQipuId) && StringUtils.isBlank(channelQipuId)) {
            return ServiceUtil.getResponseError("参数不完整");
        }
        // LIVE_CHANNEL_ID valitate,end with 22,23 the form.
        if (StringUtils.isNotBlank(channelQipuId)) {
            if (!RegUtil.isPositiveInteger(channelQipuId) || !channelQipuId.endsWith("22")) {
                return ServiceUtil.getResponseError("频道奇谱id格式错误");
            }
        }
        //LIVE_EPISODE_ID valitate,end with 23 the form
        if (StringUtils.isNotBlank(porgramQipuId)) {
            if (!RegUtil.checkProgramQipuId(porgramQipuId)) {
                return ServiceUtil.getResponseError(ERROR_PROGRAM_QIPU_ID_FORMAT);
            }
        }

        try {
            long currentTime = System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simpleDateFormat.setLenient(false);
            Date startTimeDate = null;
            Date endTimeDate = null;
            if (StringUtils.isBlank(startDate)) {
                startTimeDate = new Date(currentTime - 86400 * 6 * 1000);
                startDate = simpleDateFormat.format(startTimeDate);
            } else {
                startTimeDate = simpleDateFormat.parse(startDate);
            }
            if (StringUtils.isBlank(endDate)) {
                endTimeDate = new Date(currentTime + (long) 86400 * 60 * 1000);
                endDate = simpleDateFormat.format(endTimeDate);
            } else {
                endTimeDate = simpleDateFormat.parse(endDate);
            }
            if (!endTimeDate.after(startTimeDate)) {
                return ServiceUtil.getResponseError("结束时间必须大于开始时间");
            }
        } catch (Exception e) {
            return ServiceUtil.getResponseError(ERROR_DATE_FORMAT);
        }

        try {
            String ret = getProgramService().searchProgram(name, startDate, endDate, porgramQipuId, channelQipuId, channelName);
            if (StringUtils.isNotBlank(ret)) {
                JSONArray jsonArray = JSON.parseArray(ret);
                return Constants.getJsonResponse(Constants.CODE_SUC, jsonArray, null);
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (TException e) {
            logger.error("[searchProgram]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }

    public String programEdit(String dataString, String imageDatas) {
        TProgram entity = JSONObject.parseObject(dataString, TProgram.class);
        try {
            ProgramWebService.Iface pService = getProgramService();
            String checkResult = pService.checkEpisodeBase(entity);
            if (checkResult != null && !"success".equals(checkResult)) {
                return ServiceUtil.getResponseFail(checkResult);
            }
            if (imageDatas != null) {
                entity.setLogoUrl(imageDatas);
            }
            int maxLength = Configuration.getInt("program.name.length", 40);
            if (StringUtils.isBlank(entity.getPname())) {
                return ServiceUtil.getResponseError("节目名称不能为空");
            }
            if (entity.getPname().length() > maxLength) {
                return ServiceUtil.getResponseError("节目名称长度不能超过" + maxLength);
            }
            if (entity.getUpdateTime() == null) {
                return ServiceUtil.getResponseError("缺少属性，请刷新页面!");
            }

            TChannel tChannel = getChannelService().getById(entity.getFatherId());
            if (tChannel.getLiveType() == 2 && entity.getEpisodeGrade() == 0) {
                return ServiceUtil.getResponseFail("节目等级不能为空");
            }
            if (tChannel.getLiveType() == 2 && StringUtils.isEmpty(entity.getTabControls())) {
                return ServiceUtil.getResponseFail("移动端tab控制不能为空");
            }
            entity.setOpUser(ServiceUtil.getOpUser());
            if (entity.getOpUser() == null) {
                return ServiceUtil.getResponseFail("操作人员异常");
            }
            if (entity.getType() != 7 && pService.isInRange((int) entity.getFatherId(), entity.getStartPlayTime(), entity.getEndPlayTime(), entity.getId())) {
                return ServiceUtil.getResponseFail("时间段和已有节目覆盖");
            }

            TProgram oldEntity = pService.getById(entity.getId());
            writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_EDIT_BEFORE.getIndex(), Constants.SYSTEM_USER_SIGN, ServiceUtil.transTBaseToString(oldEntity));

            long costStart = System.currentTimeMillis();
            TResponse tResponse = pService.editProgram(entity);
            if (tResponse == null) {
                return ServiceUtil.getResponseError(INTERFACE_ERROR + ": no rpc response");
            }
            logger.info("rpc programEdit cost [{}]", System.currentTimeMillis() - costStart);
            //Constants.CODE_SUC
            int editFlag = 0;
            JSONObject errJson = JSONObject.parseObject(tResponse.getJsonData());
            editFlag = errJson.getIntValue("retValue");
            String editCode = Constants.getProgramEditCode(editFlag);
            writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_EDIT_REQ.getIndex(), null, editFlag + "|" + getStrParam());
            if (imageDatas != null) {
                String retValue = pService.productImg(entity.getId(), imageDatas);
                writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_PRODUCT_IMG.getIndex(), null, retValue + "||" + imageDatas);
            }
            if (editFlag == 0) {
                JSONObject data = new JSONObject();
                data.put("affectNum", 1);
                data.put("sportBind", errJson.getIntValue("sportBind"));
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "修改成功");
            } else {
                return ServiceUtil.getResponseFail(editCode);
            }
        } catch (Exception e) {
            logger.error("[programEdit]pid=" + entity.getId(), e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programAdd(String dataString, String imageDatas) {
        TProgram entity = JSONObject.parseObject(dataString, TProgram.class);
        ProgramWebService.Iface service = getProgramService();
        try {
            if (entity.getFatherId() == 0 ||
                    StringUtils.isEmpty(entity.getStartPlayTime()) ||
                    StringUtils.isEmpty(entity.getEndPlayTime()) ||
                    StringUtils.isEmpty(entity.getStreamStartPlayTime()) ||
                    StringUtils.isEmpty(entity.getStreamEndPlayTime()) ||
                    StringUtils.isEmpty(entity.getPname())) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            int maxLength = Configuration.getInt("program.name.length", 40);
            if (entity.getPname().length() > maxLength) {
                return ServiceUtil.getResponseError("节目名称长度不能超过" + maxLength);
            }
            int descriptionMaxLength = 400;
            if (entity.getDescription() != null && entity.getDescription().length() > descriptionMaxLength) {
                return ServiceUtil.getResponseError("节目描述长度过长");
            }

            if (entity.getEndPlayTime().compareTo(entity.getStartPlayTime()) < 1) {
                return ServiceUtil.getResponseError("节目结束时间需大于节目开始时间");
            }

            if (entity.getStreamEndPlayTime().compareTo(entity.getStreamStartPlayTime()) < 1) {
                return ServiceUtil.getResponseError("流结束时间需大于流开始时间");
            }

            if (entity.getStreamStartPlayTime().compareTo(entity.getStartPlayTime()) > 0) {
                return ServiceUtil.getResponseError("流开始时间不能大于节目开始时间");
            }

            if (entity.getStreamEndPlayTime().compareTo(entity.getEndPlayTime()) < 0) {
                return ServiceUtil.getResponseError("流结束时间不能小于节目结束时间");
            }
            if (service.isInRange((int) entity.getFatherId(), entity.getStartPlayTime(), entity.getEndPlayTime(), -1L)) {
                return ServiceUtil.getResponseFail("时间段和已有节目覆盖");
            }

            if (entity.getOaDocNo() == null) {
                return ServiceUtil.getResponseFail("必须关联oa工单");
            }

            ChannelWebService.Iface cService = getChannelService();
            TChannel tChannel = cService.getById(entity.getFatherId());
            if (tChannel.getLiveType() == 2 && entity.getEpisodeGrade() == 0) {
                return ServiceUtil.getResponseFail("节目等级不能为空");
            }
            if (tChannel.getLiveType() == 2 && StringUtils.isEmpty(entity.getTabControls())) {
                return ServiceUtil.getResponseFail("移动端tab控制不能为空");
            }
            if (tChannel.getStatus().equals("FREE") && !entity.isFreeStatus() &&
                    cService.getProgramCount(tChannel.getId()) > 0) {
                return ServiceUtil.getResponseFail("当前频道为免费频道，无法创建付费节目");
            }

            if (!tChannel.getStatus().equals("FREE") && entity.isFreeStatus()) {
                return ServiceUtil.getResponseFail("当前频道为付费频道，无法创建免费节目");
            }
            String checkResult = service.checkEpisodeBase(entity);
            if (checkResult != null && !"success".equals(checkResult)) {
                return ServiceUtil.getResponseFail(checkResult);
            }
            entity.setOpUser(ServiceUtil.getOpUser());
            if (entity.getOpUser() == null) {
                return ServiceUtil.getResponseFail("操作人员异常");
            }
            long costStart = System.currentTimeMillis();
            TResponse tResponse = service.addProgram(entity);
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            }
            logger.info("rpc addProgram cost [{}]", System.currentTimeMillis() - costStart);
            long entityId = 0;
            JSONObject errJson = JSONObject.parseObject(tResponse.getJsonData());
            entityId = errJson.getLongValue("retValue");
            if (entityId <= 0) {
                writeChannelLog(entity.getFatherId(), Constants.LogType.PROGRAM_ADD.getIndex(), null, Constants.CODE_FAIL + "|" + dataString);
            }
            if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                writeProgramLog(entityId, Constants.LogType.PROGRAM_ADD.getIndex(), null, Constants.CODE_SUC + "|" + dataString);
                if (imageDatas != null) {
                    String retValue = service.productImg(entityId, imageDatas);
                    writeProgramLog(entityId, Constants.LogType.PROGRAM_PRODUCT_IMG.getIndex(), null, retValue + "||" + imageDatas);
                }
                JSONObject data = new JSONObject();
                data.put("affectNum", 1);
                data.put("entityId", entityId);
                data.put("sportBind", errJson.getIntValue("sportBind"));
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "添加成功");
            } else {
                String msg = "";
                if (entityId == -1) {
                    msg = "节目id已存在，不能重复创建";
                } else if (entityId == -2) {
                    msg = "频道不存在";
                }
                return ServiceUtil.getResponseFail("添加失败：" + msg);
            }
        } catch (Exception e) {
            logger.error("[programAdd]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }

    }

    public String programDelete(String id) {
        if (!RegUtil.isPositiveInteger(id)) {
            return ServiceUtil.getResponseError(ERROR_PROGRAM_ID_FORMAT);
        }
        try {
            ProgramWebService.Iface service = getProgramService();
            TProgram entity = service.getById(Long.valueOf(id));
            if (entity == null) {
                return ServiceUtil.getResponseError("目标不存在");
            } else {
                boolean resultFlag = service.deleteProgram(entity.getId(), ServiceUtil.getOpUser());
                writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_DEL.getIndex(), ServiceUtil.getOpUser(), "result|" + resultFlag);
                if (resultFlag) {
                    return Constants.getJsonResponse(Constants.CODE_SUC, null, "删除成功");
                } else {
                    return ServiceUtil.getResponseFail("删除失败");
                }
            }
        } catch (Exception e) {
            logger.error("[programDelete]pid=" + id, e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipAuthCheck
    public String searchFilterProgram(String qipuId, String programName, String channelName,
                                      String startDate, String endDate, String platforms) {
        try {
            Map<String, String> params = new HashMap();
            if (!RegUtil.isDateFormat(startDate) || !RegUtil.isDateFormat(endDate)) {
                return ServiceUtil.getResponseError("时间参数错误");
            }
            if (StringUtils.isNotBlank(qipuId)) {
                if (!RegUtil.checkProgramQipuId(qipuId)) {
                    return ServiceUtil.getResponseError(ERROR_PROGRAM_QIPU_ID_FORMAT);
                }
                params.put("qipuId", qipuId);
            }
            if (!RegUtil.checkPlatform(platforms)) {
                return ServiceUtil.getResponseError("平台标识格式错误");
            }
            params.put("platforms", platforms);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            if (StringUtils.isNotBlank(programName)) {
                params.put("pname", programName);
            }
            if (StringUtils.isNotBlank(channelName)) {
                params.put("cname", channelName);
            }
            ProgramWebService.Iface service = getProgramService();
            String ret = service.searchFilterProgram(params);
            if (StringUtils.isNotBlank(ret)) {
                JSONArray jsonArray = JSON.parseArray(ret);
                return Constants.getJsonResponse(Constants.CODE_SUC, jsonArray, null);
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[searchFilterProgram]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programToggleLock(String id, String fatherId, String lockType) {
        try {
            if (!RegUtil.isPositiveInteger(id) || StringUtils.isBlank(lockType) || !RegUtil.isPositiveInteger(fatherId)) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

            int lockTypeVal = Integer.valueOf(lockType);
            if (lockTypeVal > 1) {
                return ServiceUtil.getResponseError("lockType 参数错误");
            }

            ProgramWebService.Iface service = getProgramService();
            int result = service.toggleLockProgram(Long.valueOf(id), Long.parseLong(fatherId), lockTypeVal);
            writeProgramLog(Long.parseLong(id), Constants.LogType.PROGRAM_TOGGLE_LOCK.getIndex(), null, result + "|" + getStrParam());
            if (result == 0) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else {
                return ServiceUtil.getResponseError("操作失败");
            }
        } catch (Exception e) {
            logger.error("[programToggleLock]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String programMove(String id, String flag, String fatherId, String operationDay) {

        try {    // 检查输入参数格式
            if (!RegUtil.isPositiveInteger(id) || !RegUtil.isPositiveInteger(flag) || !RegUtil.isPositiveInteger(fatherId) |
                    !RegUtil.isDateFormat(operationDay + " 00:00:00")) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

            ProgramWebService.Iface service = getProgramService();
            int result = service.moveProgram(Long.parseLong(id), Integer.parseInt(flag), Long.parseLong(fatherId), operationDay);
            writeProgramLog(Long.parseLong(id), Constants.LogType.PROGRAM_MOVE.getIndex(), null, result + "|" + getStrParam());
            if (result == 0) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else if (result == 2) {
                return ServiceUtil.getResponseError("操作失败, 时间已过，操作没有意义。");
            } else if (result == 3) {
                return ServiceUtil.getResponseError("操作失败, 已经是队列头，无法上移。");
            } else if (result == 4) {
                return ServiceUtil.getResponseError("操作失败, 已经是队列尾，无法下移。");
            } else if (result == 5) {
                return ServiceUtil.getResponseError("操作失败, 跨天节目不能上移/下移。");
            } else {
                return ServiceUtil.getResponseError("操作失败,");
            }
        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][programMove]", e);
//            insertErrorLog(e, strParam);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    //  @SkipInterfaceLog
    public String programInsertQuery(String qipuId, String pname, String startDate, String endDate,
                                     String minProgramTime, String maxProgramTime, Integer pageNo, Integer pageSize) {
        try {
            pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

            Map<String, String> params = new HashMap();
            params.put("EQI_program.is_delete", 0 + "");
            params.put("EQS_program.boss_status", "FREE");
            params.put("NEQI_channel.live_type", "3");//频道 排除 轮播台
            params.put("EQI_channel.is_enable", "1"); //频道启用状态
            if (!RegUtil.isPositiveInteger(minProgramTime)) {
                return ServiceUtil.getResponseError("最小节目时长格式错误");
            }
            // second
            if (Long.valueOf(minProgramTime).intValue() < 60) {
                return ServiceUtil.getResponseError("最小节目时长时间不能小于" + 60 + "秒");
            }
            params.put("GEI_TIMESTAMPDIFF(SECOND,program.start_play_time,program.stop_play_time) ", minProgramTime);
            if (StringUtils.isNotEmpty(maxProgramTime)) {
                if (!RegUtil.isPositiveInteger(maxProgramTime)) {
                    return ServiceUtil.getResponseError("最大节目时长格式错误");
                }
                if (Long.valueOf(maxProgramTime).longValue() < Long.valueOf(minProgramTime).longValue()) {
                    return ServiceUtil.getResponseError("最大节目时长不能小于最小节目时长");
                }
                params.put("LEI_TIMESTAMPDIFF(SECOND,program.start_play_time,program.stop_play_time) ", maxProgramTime);
            }

            if (StringUtils.isNotEmpty(startDate)) {
                if (!RegUtil.isDateFormat(startDate)) {
                    return ServiceUtil.getResponseError(PARAMETER_ERROR);
                }
                params.put("GET_program.start_play_time", startDate);
            }

            if (StringUtils.isNotEmpty(endDate)) {
                if (!RegUtil.isDateFormat(endDate)) {
                    return ServiceUtil.getResponseError(PARAMETER_ERROR);
                }
                params.put("LET_program.start_play_time", endDate);
            }

            if (StringUtils.isNotEmpty(qipuId)) {
                if (!RegUtil.checkProgramQipuId(qipuId)) {
                    return ServiceUtil.getResponseError("奇谱Id 参数错误");
                }
                params.put("EQL_program.qipu_id", qipuId);
            }
            if (StringUtils.isNotEmpty(pname)) {
                params.put("LIKES_program.program_name", pname.trim());
            }

            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "start_play_time", "desc", true);
            ProgramWebService.Iface service = getProgramService();
            TProgramPage tProgramPage = service.findProgramPage(page, tFilter);
            boolean success = tProgramPage != null;
            if (success) {
                return Constants.getResponse(Constants.CODE_SUC, tProgramPage, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError("查询失败");
            }
        } catch (Exception e) {
            logger.error("[programInsertQuery]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String programIndexMove(String id, String aimId, String dateTime, String channelId) {
        if (!RegUtil.isPositiveInteger(channelId)) {
            return ServiceUtil.getResponseError(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isShortDateFormat(dateTime)) {
            return ServiceUtil.getResponseError("操作时间错误");
        }
        try {
            int resultType = getProgramService().indexMove(Long.valueOf(id), Long.valueOf(aimId), dateTime, Long.valueOf(channelId));
            writeProgramLog(Long.valueOf(id), Constants.LogType.PROGRAM_INDEX_MOVE.getIndex(), null, resultType + "|" + getStrParam());
            switch (resultType) {
                case 1:
                    return Constants.getJsonResponse(Constants.CODE_SUC, null, "修改成功");
                case -1:
                    return ServiceUtil.getResponseFail("修改失败:无法定位插入目标!");
                case -2:
                case -3:
                    return ServiceUtil.getResponseFail("修改失败:没有找到目标！");
                case -4:
                case -5:
                    return ServiceUtil.getResponseFail("修改失败:相关目标已被锁定！");
                case -6:
                    return ServiceUtil.getResponseFail("修改失败:不支持直播对象！");
                case -7:
                    return ServiceUtil.getResponseFail("修改失败:异常的节目开始时间,节目结束时间！");
                default:
                    return ServiceUtil.getResponseFail("修改失败:无法定位插入目标");
            }

        } catch (Exception e) {
            logger.error("[indexMove][id=" + id + "][aimId=" + aimId + "]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programBatchDel(String ids, String dateTime, String channelId) {
        if (!RegUtil.isPositiveInteger(channelId)) {
            return ServiceUtil.getResponseFail(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isShortDateFormat(dateTime)) {
            return ServiceUtil.getResponseFail("操作时间错误");
        }
        try {
            List<Long> idList = JSONArray.parseArray(ids, Long.class);
            int resultType = getProgramService().batchDel(idList, dateTime, Long.valueOf(channelId));
            writeChannelLog(Long.valueOf(channelId), Constants.LogType.PROGRAM_BATCH_DEL.getIndex(), null, resultType + "|" + getStrParam());
            switch (resultType) {
                case 1:
                    return Constants.getJsonResponse(Constants.CODE_SUC, null, "批量删除成功");
                case -1:
                    return ServiceUtil.getResponseFail("批量删除失败");
                default:
                    return ServiceUtil.getResponseFail("批量删除失败");
            }
        } catch (Exception e) {
            logger.error("[programBatchDel][ids=" + ids, e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programBatchAdd(String dataString, String beginTime, String fatherId) {
        if (!RegUtil.isPositiveInteger(fatherId)) {
            return ServiceUtil.getResponseFail(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isDateFormat(beginTime)) {
            return ServiceUtil.getResponseFail(ERROR_DATE_FORMAT);
        }
        try {
            List<Long> idList = JSONArray.parseArray(dataString, Long.class);
            String result = getProgramService().batchAdd(idList, beginTime, Long.valueOf(fatherId));
            writeChannelLog(Long.valueOf(fatherId), Constants.LogType.PROGRAM_REFER_INSERT.getIndex(), null, result + "|" + getStrParam());
            if ("success".equals(result)) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "插入成功");
            } else {
                return ServiceUtil.getResponseError("插入失败:" + result);
            }
        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][programBatchAdd]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipInterfaceLog
    public String getProgramBroadcastControl(long programId) {
        try {
            BroadcastControlWebService.Iface service = getBroadcastService();
            List<TProgramPlatformControl> tProgramPlatformControls = service.getProgramPlatControls(programId);
            if (tProgramPlatformControls != null) {
                return Constants.getJsonResponse(Constants.CODE_SUC, tProgramPlatformControls, null);
            } else {
                return ServiceUtil.getResponseFail("获取失败");
            }
        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][getProgramBroadcastControl]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String setProgramBroadcastControl(long programId, String params, long channelId) {

        try {
            JSONObject paramsObject = JSONObject.parseObject(params);
            if (null == paramsObject || !paramsObject.containsKey("platform") ||
                    StringUtils.isEmpty(paramsObject.getString("platform"))) {
                return Constants.getJsonResponse(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
            }
            List<TProgramPlatformControl> tProgramPlatformControls = new ArrayList<>();
            TProgramPlatformControl model = new TProgramPlatformControl();
            model.setProgramId(programId);
            model.setPlatform(paramsObject.getInteger("platform"));
            // 暂时只可设置上下线状态、直播延时、地区黑名单
            model.setIsDownloadAllowed(true);
            model.setIsDrm(false);
            model.setIsShareAllowed(true);
            model.setIsCooperationAllowed(true);
            model.setRejectSearch(Boolean.valueOf(paramsObject.getString("rejectSearch")));
            model.setRejectTop(false);
            model.setRejectRecommend(false);
            try {
                model.setLiveDelayTime(paramsObject.containsKey("liveDelayTime") ? paramsObject.getInteger("liveDelayTime") : 0);
            } catch (Exception e) {
                return Constants.getJsonResponse(Constants.CODE_ERROR_PARAM, null, "liveDelayTime参数错误");
            }
            model.setIpSegmentDelayTime(0);
            model.setRegionRejectSearch(Boolean.valueOf(paramsObject.getString("regionRejectSearch")));
            model.setAvailableStatus(Boolean.valueOf(paramsObject.getString("availableStatus")));
            if (paramsObject.containsKey("blacklist")) {
                model.setBlacklist(paramsObject.getString("blacklist"));
            }
            tProgramPlatformControls.add(model);
            BroadcastControlWebService.Iface service = getBroadcastService();
            boolean flag = service.setProgramPlatControls(programId, tProgramPlatformControls);
            writeProgramLog(programId, Constants.LogType.PROGRAM_BROADCAST.getIndex(), ServiceUtil.getOpUser(), (flag ? "success" : "fail") + "|" + params);
            if (flag) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "设置成功");
            }
            return ServiceUtil.getResponseError("设置失败");
        } catch (Exception e) {
            logger.error("[setProgramBroadcastControl]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }

    }

    @SkipInterfaceLog
    public String getLivingInfo() {
        try {
            ProgramWebService.Iface service = getProgramService();
            List<TLivingInfo> result = service.getTLivingInfo();
            if (null != result) {
                return Constants.getResponseList(Constants.CODE_SUC, result, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getLivingInfo]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programSyncTVMao(String fatherId) {
        try {
            if (fatherId == null || !RegUtil.isNonnegativeInteger(fatherId)) {
                return ServiceUtil.getResponseFail("频道ID必须为整数");
            }
            ProgramWebService.Iface service = getProgramService();
            long useFatherId = Long.valueOf(fatherId);
            boolean resultFlag = service.queryAssignProgramList(useFatherId);
            writeChannelLog(useFatherId, Constants.LogType.PROGRAM_GET_TVMAO.getIndex(), "0", (resultFlag ? Constants.CODE_SUC : Constants.CODE_FAIL) + "|" + getStrParam());
            if (resultFlag) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "更新成功");
            } else {
                return ServiceUtil.getResponseFail("更新失败");
            }
        } catch (Exception e) {
            logger.error("[programSyncTVMao]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String syncProgram(String fatherId, String programId) {
        long useProgramId = -1;
        try {
            if (fatherId == null || !RegUtil.isNonnegativeInteger(fatherId)) {
                return ServiceUtil.getResponseFail("频道ID必须为整数");
            }
            if (programId != null && RegUtil.isNonnegativeInteger(fatherId)) {
                useProgramId = Long.valueOf(programId);
            }
            ProgramWebService.Iface service = getProgramService();
            long useFatherId = Long.valueOf(fatherId);
            service.forceSyncProgramList(useFatherId, useProgramId);
            writeChannelLog(useFatherId, Constants.LogType.PROGRAM_SYNC.getIndex(), "0", Constants.CODE_SUC + "|" + getStrParam());
            return Constants.getJsonResponse(Constants.CODE_SUC, null, "更新成功");
        } catch (Exception e) {
            logger.error("[syncProgram]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipAuthCheck
    public String proxyToPuYu(String barCode, String cprVideoName) {
        try {
            ProgramWebService.Iface service = getProgramService();
            if (barCode == null) {
                barCode = "";
            }
            if (cprVideoName == null) {
                cprVideoName = "";
            }
            String retValue = service.proxyToPuYu(barCode, cprVideoName);
            if (retValue != null) {
                return Constants.getJsonResponse(Constants.CODE_SUC, retValue, null);
            } else {
                return ServiceUtil.getResponseError("查询璞玉失败");
            }
        } catch (Exception e) {
            logger.error("[EPG][API][proxyToPuYu][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String programDaySort(String fatherId, String sortDate) {
        if (!RegUtil.isPositiveInteger(fatherId)) {
            return ServiceUtil.getResponseError(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isDateFormat(sortDate)) {
            return ServiceUtil.getResponseError(ERROR_DATE_FORMAT);
        }
        try {
            ProgramWebService.Iface service = getProgramService();
            String result = service.daySortProgram(Long.valueOf(fatherId), sortDate);
            if ("success".equals(result)) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else {
                return ServiceUtil.getResponseError("操作失败|" + result);
            }

        } catch (Exception e) {
            logger.error("[programDaySort]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String programForceCheck(long programId) {
        try {
            ProgramWebService.Iface service = getProgramService();
            int ret = service.programForceCheck(programId);
            switch (ret) {
                case -1:
                    return ServiceUtil.getResponseError("设置失败");
                default:
                    return Constants.getJsonResponse(Constants.CODE_SUC, ret, "设置成功");
            }
        } catch (Exception e) {
            logger.error("[programForceCheck]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipAuthCheck
    public String recordStreamError(String errorCode, String channelId, String programId, String obj, String errorAll) {
        if (StringUtils.isBlank(obj) || StringUtils.isBlank(errorAll)) {
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
        if (!RegUtil.isNonnegativeInteger(errorCode)) {
            return ServiceUtil.getResponseError("errorCode 类型异常");
        }
        if (!RegUtil.isPositiveInteger(channelId)) {
            return ServiceUtil.getResponseError(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isPositiveInteger(programId)) {
            return ServiceUtil.getResponseError(ERROR_PROGRAM_ID_FORMAT);
        }

        try {
            int errorVal = Integer.valueOf(errorCode);
            if (errorVal < 0 || errorVal > 4) {
                return ServiceUtil.getResponseError("错误类型异常");
            }
            int errorAllVal = Integer.valueOf(errorAll);
            String streamName = "";
            if (1 != errorAllVal) {
                streamName = obj.split("/live/")[1];
            }

            ProgramWebService.Iface service = getProgramService();
            int result = service.saveStreamError(errorVal, Long.valueOf(channelId), Long.valueOf(programId), streamName, errorAllVal);

            if (0 == result) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else {
                return ServiceUtil.getResponseError(ERROR_EXIST);
            }
        } catch (Exception e) {
            logger.error("[EPG][API][recordStreamError][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    // 当前频道之后最大的时长节目信息
    @SkipAuthCheck
    public String programMaxDuration(String fatherId) {
        if (!RegUtil.isPositiveInteger(fatherId)) {
            return ServiceUtil.getResponseError(ERROR_CHANNEL_ID_FORMAT);
        }
        try {
            ProgramWebService.Iface service = getProgramService();
            String result = service.getMaxDurationProgram(Long.valueOf(fatherId));
            return Constants.getJsonResponse(Constants.CODE_SUC, null == result ? "" : result, "获取成功");
        } catch (Exception e) {
            logger.error("[programMaxDuration]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String getYesterdayEndTime(String channelId, String newStartTime) {
        if (!RegUtil.isPositiveInteger(channelId)) {
            return ServiceUtil.getResponseError(ERROR_CHANNEL_ID_FORMAT);
        }
        if (!RegUtil.isPositiveInteger(newStartTime)) {
            return ServiceUtil.getResponseError("毫秒数格式错误");
        }
        try {
            ProgramWebService.Iface service = getProgramService();
            long result = service.getYesterdayEndTime(Long.valueOf(channelId), Long.valueOf(newStartTime));
            if (result > 0) {
                return Constants.getJsonResponse(Constants.CODE_SUC, result, "操作成功");
            } else {
                return ServiceUtil.getResponseError("获取数据失败");
            }
        } catch (Exception e) {
            logger.error("[EPG][API][getYesterdayEndTime][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }


    @SkipAuthCheck
    public String snapshotCall(String taskId, String snapshot, String errcode, String errmsg) {
        if (!RegUtil.isPositiveInteger(taskId)) {
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
        try {
            ProgramWebService.Iface programService = getProgramService();
            String retValue = programService.snapshot(Long.valueOf(taskId), snapshot, errcode, errmsg);
            if (Constants.CODE_SUC.equals(retValue)) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, Constants.getCode(retValue));
            } else {
                return ServiceUtil.getResponseError(retValue);
            }
        } catch (Exception e) {
            logger.error("[snapshotCall]", e);
            return ServiceUtil.getResponseError(INTERFACE_ERROR);
        }
    }


    public String modifyAdvert(Long programId, Integer enable) {
        try {
            ProgramWebService.Iface service = getProgramService();
            if (programId == null || enable == null) {
                return ServiceUtil.getResponseFail(PARAMETER_ERROR);
            } else {
                int retValue = service.modifyAdvert(programId, enable);
                String editCode = Constants.getAdvertEditCode(retValue);
                writeProgramLog(programId, Constants.LogType.PROGRAM_ADVERT_MODIFY.getIndex(), null, (retValue == 0 ? Constants.CODE_SUC : Constants.CODE_FAIL) + "|" + getStrParam());
                if (retValue == 0) {
                    return Constants.getJsonResponse(Constants.CODE_SUC, null, editCode);
                } else {
                    return ServiceUtil.getResponseFail(editCode);
                }
            }
        } catch (Exception e) {
            logger.error("[modifyAdvert]", e);
            return ServiceUtil.getResponseFail(INTERFACE_ERROR);
        }
    }

    @SkipAuthCheck
    public String updateBySport(String programQipuId, String newStartTime, String newStopTime) {
        try {
            ProgramWebService.Iface service = getProgramService();
            if (!RegUtil.checkProgramQipuId(programQipuId) || !RegUtil.isDateFormat(newStartTime) || !RegUtil.isDateFormat(newStopTime) || newStartTime.compareTo(newStopTime) > 1) {
                return ServiceUtil.getResponseFail(PARAMETER_ERROR);
            }
            Map<String, String> params = new HashMap<String, String>();
            params.put("EQL_program.qipu_id", programQipuId);
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, 1, 1, "id", "asc", false);
            TProgramPage tProgramPage = service.findProgramPage(page, tFilter);
            TProgram entity = null;
            if (tProgramPage.getResult().size() == 1) {
                entity = tProgramPage.getResult().get(0);
            }
            if (entity == null) {
                return ServiceUtil.getResponseFail(DETAIL_ERROR_NO_ENTITY);
            }
            if (entity.getMatchSummary() == null || entity.getMatchSummary().length() == 0) {
                return Constants.getJsonResponse(Constants.CODE_ERROR_THIRD_SPORT_UPDATETIME, null, Constants.getCode(Constants.CODE_ERROR_THIRD_SPORT_UPDATETIME));
            }
            writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_EDIT_BEFORE.getIndex(), Constants.SYSTEM_USER_SIGN, ServiceUtil.transTBaseToString(entity));
            entity.setStartPlayTime(newStartTime);
            entity.setEndPlayTime(newStopTime);
            if (newStartTime.compareTo(entity.getStreamStartPlayTime()) < 0) {
                entity.setStreamStartPlayTime(newStartTime);
            }
            if (newStopTime.compareTo(entity.getStreamEndPlayTime()) > 0) {
                entity.setStreamEndPlayTime(newStopTime);
            }
            long costStart = System.currentTimeMillis();
            TResponse tResponse = service.editProgram(entity);
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            }
            logger.info("rpc updateBySport cost [{}]", System.currentTimeMillis() - costStart);
            int editFlag = 0;
            JSONObject errJson = JSONObject.parseObject(tResponse.getJsonData());
            editFlag = errJson.getIntValue("retValue");
            String editCode = Constants.getProgramEditCode(editFlag);
            writeProgramLog(entity.getId(), Constants.LogType.PROGRAM_EDIT_BY_SPORT.getIndex(), null, editFlag + "|" + getStrParam());
            if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                JSONObject data = new JSONObject();
                data.put("affectNum", 1);
                data.put("sportBind", errJson.getIntValue("sportBind"));
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "修改成功");
            } else {
                return ServiceUtil.getResponseFail(editCode);
            }
        } catch (Exception e) {
            logger.error("[updateBySport]", e);
            return ServiceUtil.getResponseFail(INTERFACE_ERROR);
        }
    }

    public String unbindSport(String programQipuId, String matchId) {
        try {
            ProgramWebService.Iface service = getProgramService();
            if (!RegUtil.checkProgramQipuId(programQipuId) || !RegUtil.isInteger(matchId)) {
                return ServiceUtil.getResponseFail(PARAMETER_ERROR);
            }
            TResponse tResponse = service.unbindSport(Long.valueOf(programQipuId), Long.valueOf(matchId));
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            }
            JSONObject jsonData = JSONObject.parseObject(tResponse.getJsonData());
            if (jsonData.getLongValue("entityId") > 0) {
                writeProgramLog(jsonData.getLongValue("entityId"), Constants.LogType.PROGRAM_UNBIND_SPORT.getIndex(), null, tResponse.getJsonData() + "|" + getStrParam());
            }
            if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "解绑成功");
            } else {
                return ServiceUtil.getResponseFail("操作失败");
            }
        } catch (Exception e) {
            logger.error("[unbindSport]", e);
            return ServiceUtil.getResponseFail(INTERFACE_ERROR);
        }
    }

    @SkipAuthCheck
    public String saveOAInfo(String dataString) {
        try {
            TInfoOA entity = JSONObject.parseObject(dataString, TInfoOA.class);
            ProgramWebService.Iface service = getProgramService();
            if (null == entity.getDocNo()) {
                return ServiceUtil.getResponseFail(PARAMETER_ERROR);
            }
            TResponse tResponse = service.saveOAInfo(entity);
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            }
            if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "更新成功");
            } else {
                return ServiceUtil.getResponseFail("操作失败");
            }
        } catch (Exception e) {
            logger.error("[saveOAInfo]", e);
            return ServiceUtil.getResponseFail(INTERFACE_ERROR);
        }
    }
}
